/**
 * ECP Web开发 通用控件.
 * Copyright(c) 2012-2020 YGSoft.Inc
 * Author:wugang5@ygsoft.com
 * Date:2016/6/27
 */
define(["jquery","ecp.utils.i18n"], function($,locale){
	/**
	 * 搜索模板
	 */
	"use strict";
	var template =  '<div class="input-icon" style="width: {width};">' +
						'{searchIcon}' +
						'<i id="clearIcon" class="fa fa-times-circle" style="color: #888888 !important; cursor: pointer; right: 8px; display: block;"></i>' +
						'<input id="search" type="text" class="form-control {inputClass}" placeholder={placeholder}>' +
					'</div>';

	var defaults = {
       width : '280px',
       placeholder :locale.Control.search,
       container : '',
       inputClass : '',
	   showSearchIcon: true,
       callback : function(){}
	};
	function Plugin(options){
		this.options = $.extend({}, defaults, options || {});
		this.container = $(this.options.container);
		if(this.container.length){
			this.template = template.replace(/{width}/g,this.options.width).replace(/{searchIcon}/g, this.options.showSearchIcon ? '<i class="fa fa-search"></i>' : '')
										.replace(/{inputClass}/g, this.options.inputClass).replace(/{placeholder}/g, this.options.placeholder);
			this.show = function(){
				this.container.html(this.template);
				var $clearIcon = $('#clearIcon', this.container);
				var $search = this.$search = $('#search', this.container);
				if(!this.options.showSearchIcon){
					//修改默认padding
					$search.attr("style", "padding-left:12px !important");
				}
				$search.attr("value", "");
				$clearIcon.hide();
				$clearIcon.on('click', function(){
					var $this = $(this);
					$search.val("").focus();
					$this.fadeOut("fast").hide();
					(typeof options.callback === 'function') && options.callback.call(this, "");
				});
				var isEnterKey = false;
				$search.off('keyup').on('keyup', function(event){
					var e = event || window.event;
					var $this = $(this);
					var searchVal = $this.val();
					if(searchVal == ''){
						$clearIcon.fadeOut("fast").hide(); 
					}else{
						$clearIcon.fadeIn("fast").show(); 
					}
					isEnterKey = false;
					if(e.keyCode == 13){
						isEnterKey = true;
						(typeof options.callback === 'function') && options.callback.call(this, searchVal);
					} else {
						//连续输入清除定时器
						if(this.timeoutID){
							clearTimeout(this.timeoutID);
						}
						this.timeoutID = setTimeout(function(){
							if(!isEnterKey){
								(typeof options.callback === 'function') && options.callback.call(this, searchVal);
							}
						},300);
					}
				});
				this.value = this.$search && this.$search.val();
			};
		}
	}
	return {
		render : function(options){
			var plugin = new Plugin(options);
			plugin.show && plugin.show();
			return plugin;
		}
	};
});
